<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
               label-width="100px">
        <el-form-item label="个人用户代码" prop="identityCode">
          <el-input
            v-model="queryParams.identityCode"
            placeholder="请输入个人用户代码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!--        <el-form-item label="分公司名称" prop="corporateName">-->
        <!--          <el-select v-model="queryParams.corporateName" filterable placeholder="请选择分公司名称">-->
        <!--            <el-option-->
        <!--              v-for="item in companyList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.corporateName"-->
        <!--              :value="item.corporateName"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            size="mini"
            @click="handleAdd('1')"
            v-hasPermi="['system:userInfo:add']"
          >开户参与分销 {{ distributionData.userNum }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAdd('0')"
            v-hasPermi="['system:userInfo:add']"
          >开户不参与分销 {{ distributionData.notUserNum }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['system:userInfo:add']"
                     @click="handleAdd('2')">开启先用后付
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-edit"
                     v-hasPermi="['system:userInfo:edit']"
                     size="mini" @click="handleUpdate">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">

          <el-button type="danger" plain icon="el-icon-delete" v-hasPermi="['system:userInfo:remove']" size="mini"
                     @click="handleDelete">删除
          </el-button>
        </el-col>
        <!--        <el-col :span="1.5" class="mr10 text-info">-->
        <!--          参与分销额度：<span>{{ distributionData.userNum }}</span>-->
        <!--        </el-col>-->
        <!--        <el-col :span="1.5" class="text-danger">-->
        <!--          不参与分销额度：<span>{{ distributionData.notUserNum }}</span>-->
        <!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="personalList" @selection-change="handleSelectionChange" border stripe>
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="个人用户代码" align="center" prop="identityCode"/>
        <el-table-column label="用户名" align="center" prop="realName"/>
        <el-table-column label="手机号码" align="center" prop="userMobile"/>
        <el-table-column label="所属分公司" align="center" prop="parentBranchId" width="120">
          <template slot-scope="scope">
            {{ scope.row.parentBranchId ? scope.row.parentBranchName : "无" }}
          </template>
        </el-table-column>
        <el-table-column label="所属代理" align="center" prop="parentAgentId" width="120">
          <template slot-scope="scope">
            {{ scope.row.parentAgentId ? scope.row.parentAgentName : "无" }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="直推个人" align="center" prop="parentId" width="120">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ scope.row.parentId ? scope.row.parentId : "暂无" }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="到期时间" align="center" prop="expirationTime" width="120"/>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="branchForm" :model="branchForm" :rules="branchRules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名：" prop="userName">
              <el-input v-model="branchForm.userName" placeholder="请输入用户名称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱：" prop="email">
              <el-input v-model="branchForm.email" placeholder="请输入电子邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码：" prop="phonenumber">
              <el-input v-model="branchForm.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名：" prop="realName">
              <el-input v-model="branchForm.realName" placeholder="请输入真实姓名" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.identityCode">
          <el-col :span="12">
            <el-form-item label="密码：" prop="password">
              <el-input v-model="branchForm.password" placeholder="请输入密码" type="password" maxlength="20"
                        show-password autocomplete="new-password"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码：" prop="surePassword">
              <el-input v-model="branchForm.surePassword" placeholder="请输入确认密码" type="password" maxlength="20"
                        show-password autocomplete="new-password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.identityCode">
          <el-col :span="12">
            <el-form-item label="所属分公司：" prop="parentBranchId">
              <el-select v-if="userInfo.userId == 1" v-model="branchForm.parentBranchId" filterable
                         placeholder="请选择所属分公司" @change="chooseBranch">
                <el-option
                  v-for="item in companyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
              <el-input v-else v-model="branchForm.parentBranchId" disabled placeholder="请输入所属分公司"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属代理：" prop="parentAgentId">
              <el-select v-model="branchForm.parentAgentId" filterable
                         placeholder="请选择所属代理" @change="getPersonalList">
                <el-option
                  v-for="item in pushAgentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.identityCode">
          <el-col :span="12">
            <el-form-item label="直推个人：" prop="parentId">
              <el-select v-model="branchForm.parentId" filterable :disabled="branchForm.identityCode!=''"
                         placeholder="请选择直推个人">
                <el-option
                  v-for="item in parentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务时间：" prop="buyType">
              <el-radio-group v-model="branchForm.buyType" @input="changeRadio">
                <el-radio :label="1">100元普通版</el-radio>
                <el-radio :label="2">2800年版</el-radio>
                <el-radio :label="3">12800年版</el-radio>
                <el-radio :label="9">先用后付</el-radio>
                <el-radio :label="99">免费版</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.identityCode">
          <!--          <el-col :span="12" v-if="branchForm.expirationType == 2 || branchForm.expirationType == 3">-->
          <!--            <el-form-item label="是否开启分销：" prop="isDistribution">-->
          <!--              <el-switch-->
          <!--                :disabled="distributionData.userNum == 0"-->
          <!--                v-model="branchForm.isDistribution"-->
          <!--                active-text="开启"-->
          <!--                active-value="1"-->
          <!--                inactive-value="0"-->
          <!--                inactive-text="不开启"-->
          <!--                active-color="#13ce66"-->
          <!--                inactive-color="#ff4949">-->
          <!--              </el-switch>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12" v-if="branchForm.buyType == 4">
            <el-form-item label="服务到期时间：" prop="expirationTime">
              <el-date-picker
                v-model="branchForm.expirationTime"
                type="datetime"
                placeholder="选择服务到期时间"
                :disabled="branchForm.buyType != 4"
                default-time="23:59:59">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="是否自动刊登：" prop="isPublish">-->
        <!--              <el-switch-->
        <!--                v-model="branchForm.isPublish"-->
        <!--                active-text="开启"-->
        <!--                inactive-text="关闭"-->
        <!--                active-color="#13ce66"-->
        <!--                inactive-color="#ff4949">-->
        <!--              </el-switch>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="是否加入奖金池：" prop="bonusPool">-->
        <!--              <el-switch-->
        <!--                v-model="branchForm.bonusPool"-->
        <!--                active-text="加入"-->
        <!--                inactive-text="不加入"-->
        <!--                active-color="#13ce66"-->
        <!--                inactive-color="#ff4949">-->
        <!--              </el-switch>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证正反面：" prop="agentIdCard">
              <image-upload v-model="branchForm.agentIdCard" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传合同：" prop="contract">
              <image-upload v-model="branchForm.contract" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传证书：" prop="certificate">
              <image-upload v-model="branchForm.certificate" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addInfo,
  queryList,
  queryInfo,
  editInfo,
  deleteInfo,
  queryBranchList,
  queryBranchAndAgent,
  queryAgentList,
  queryUserInfoByAgentIdagentId,
  queryUserInfoByBranchId, queryDistributionLimit
} from "@/api/organize/personal";
import {queryAgentByBranchId, queryCompanyList} from "@/api/organize/agent";
import {formatDate} from "@/utils/index"

export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.branchForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      loading: true,// 遮罩层
      ids: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0,// 总条数
      companyList: [],//分公司列表
      parentList: [],//上级公司列表
      agentList: [],//代理公司列表
      personalList: [],//个人列表
      pushAgentList: [],//所属代理列表
      title: "",// 弹出层标题
      open: false,// 是否显示弹出层
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
      },
      // 表单校验
      branchRules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        password: [{required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}],
        surePassword: [{required: true, message: "确认密码不能为空", trigger: "blur"},
          {validator: equalToPassword, required: true, trigger: "blur"},],
        email: [{required: true, type: "email", message: "请输入正确的邮箱地址", trigger: "blur"}],
        phonenumber: [{
          required: true,
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }],
        realName: [{required: true, message: "真实姓名不能为空", trigger: "blur"}],
        legalPerson: [{required: true, message: "法人姓名不能为空", trigger: "blur"}],
        corporateName: [{required: true, message: "公司名称不能为空", trigger: "blur"}],
        parentBranchId: [{required: true, message: "所属分公司不能为空", trigger: "blur"}],
        parentAgentId: [{required: false, message: "所属代理不能为空", trigger: "change"}],
        parentId: [{required: false, message: "请选择直推个人", trigger: "change"}],
        buyType: [{required: true, message: "服务时间不能为空", trigger: "change"}],
        creditCode: [{required: true, message: "信用代码不能为空", trigger: "blur"}],
        contract: [{message: "合同不能为空", trigger: "change"}],
        certificate: [{message: "证书不能为空", trigger: "change"}],
        agentIdCard: [{required: false, message: "身份证不能为空", trigger: "change"}],
        businessLicense: [{required: true, message: "营业执照不能为空", trigger: "change"}],
        expirationTime: [{required: true, message: "请选择服务到期时间", trigger: "change"}],
        isPublish: [{required: true, message: "请选择是否自动刊登", trigger: "change"}],
        bonusPool: [{required: true, message: "请选择是否加入奖金池", trigger: "change"}],
      },
      branchForm: {},// 个体户表单信息
      userInfo: "",
      branchInfo: {},
      distributionData: '',
      isJoinDistribution: 0,//是否参与分销
      isPay: undefined
    };
  },
  created() {
    this.userInfo = this.$store.state.user.urserInfo
    this.getList();
    this.getCompanyList()
    // this.getAgentList() //查询代理列表
    if (this.userInfo.userId != 1) {
      this.getAgentAndPersonal()
    }
  },
  methods: {
    // 获取分公司下个人和代理可分销额度
    getDistributionNum() {
      queryDistributionLimit().then(res => {
        this.distributionData = res.data
      })
    },
    // 获取分公司下个人和代理列表
    getAgentAndPersonal() {
      queryUserInfoByBranchId().then(res => {
        console.log('查询分公司下代理和个人列表', res)
        // this.companyList = res.branch
        this.pushAgentList = res.agent
        this.parentList = res.user
        if (res.branch) {
          this.branchInfo = res.branch[0]
        }
      })
    },

    // 查询分公司和总公司列表
    getCompanyList() {
      this.loading = true;
      queryCompanyList(this.queryParams).then(response => {
          this.companyList = response;
          // this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 通过分公司查询代理列表
    chooseBranch(e) {
      queryAgentByBranchId({parentBranchId: e}).then(res => {
        this.pushAgentList = res
      })
    },
    // 通过代理查询个人用户列表
    getPersonalList(e) {
      let data = {
        parentAgentId: e
      }
      console.log()
      queryUserInfoByAgentIdagentId(data).then(res => {
        this.parentList = res
      })
    },
    // 选择服务时间
    changeRadio(e) {
      console.log('eeee', e)
      // let nowDate = new Date().getTime()
      // if (e == 3) {
      //   nowDate = nowDate + 1000 * 60 * 60 * 24 * 30
      // }
      // let newDate = formatDate(nowDate);
      //
      // console.log("当前日期", newDate);
      // console.log('nowDate', nowDate.toLocaleString())
      // if (e == 3) {
      //   this.branchForm.expirationTime = e
      // }
    },
    getAgentList() {
      queryAgentList().then(res => {
        this.agentList = res.rows
      })
    },

    // 查询代理公司列表
    getList() {
      this.loading = true;
      queryList(this.queryParams).then(response => {
          let data = response.rows
          if (data && data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              data[i]['expirationTime'] = formatDate(data[i].expirationTime)
            }
          }
          this.personalList = data;
          this.total = response.total;
          this.loading = false;
          this.getDistributionNum()
        }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.branchForm = {
        corporateName: undefined,//公司名称
        legalPerson: undefined,//法人姓名
        userName: undefined,//用户名
        creditCode: undefined,//信用代码
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        identityCode: "",//公司代码
        agentIdCard: "",//身份证正反面
        contract: "",//合同
        certificate: undefined,//证书
        isDistribution: this.isJoinDistribution,//是否参与分销
        isPay: this.isPay
      };
      this.branchForm.parentBranchId = this.branchInfo.value

      this.resetForm("branchForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(e) {
      this.isPay = undefined;
      if (e == 1) {
        if (this.distributionData.userNum == 0) {
          this.$message.error('名额不足！')
          return
        }
      } else if (e == 2) {
        this.isPay = 1
      } else {
        if (this.distributionData.notUserNum == 0) {
          this.$message.error('名额不足！')
          return
        }
      }
      this.reset();
      this.isJoinDistribution = e
      this.title = e == 1 ? "参与分销个人开户" : "不参与分销个人开户";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      queryInfo(row.id).then(response => {
        this.branchForm = response.data;
        this.open = true;
        this.title = "修改个人ERP信息";
        // this.branchForm.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["branchForm"].validate(valid => {
        if (valid) {
          // if (this.branchForm.parentId) {
          //   let index = this.branchForm.parentId.length
          //   this.branchForm.parentId = this.branchForm.parentId[index - 1]
          // }
          this.branchForm.expirationTime = new Date(this.branchForm.expirationTime)
          // let cardIdList = this.branchForm.agentIdCard.split(';')
          // if (cardIdList && cardIdList.length != 2) {
          //   this.$message.error('身份证照片数量不正确！')
          //   return
          // }
          // if (this.branchInfo) {
          //   this.branchForm.parentBranchId = this.branchInfo.value
          // }
          let data = {
            distributionUser: this.branchForm,
            distributionUserBasicInfo: this.branchForm,
            user: {
              phonenumber: this.branchForm.phonenumber,
              email: this.branchForm.email,
              password: this.branchForm.password,
              surePassword: this.branchForm.surePassword,
              userName: this.branchForm.userName,
            },
            // 需要检查，获取不到
            isDistribution: this.branchForm.isDistribution,
            // 固定模式分销，暂不考虑自定义
            distributionMode: 0
          }
          if (this.branchForm.identityCode) {
            editInfo(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('this.ids', this.ids)
      const ids = row.id || this.ids.toString();
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
<style>
.radio-box {
  margin-bottom: 5px;
}
</style>
